//
//  BQListViewController.m
//  BeeQuick
//
//  Created by AaronWei on 2017/7/9.
//  Copyright © 2017年 BecomeRich. All rights reserved.
//

#import "BQListViewController.h"
#import "UILabel+Addition.h"
#import "UIColor+MLAddition.h"
#import "BQAccountManager.h"
#import "BQCategoryModel.h"
#import "BQCategoryTableViewCell.h"
#import "BQProductTableViewCell.h"
#import "BQDetailViewController.h"

@interface BQListViewController () <UITableViewDelegate, UITableViewDataSource,CAAnimationDelegate>

@property (copy, nonatomic) NSArray<BQCategoryModel *> *categories;

@property (weak, nonatomic) UIView *backgroundView;

@property (weak, nonatomic) UITableView *categoryTableView;

@property (weak, nonatomic) UITableView *productTableView;

@end

static NSString *category_id = @"category";
static NSString *product_id = @"product";

@implementation BQListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.navigationController.navigationBar setBackgroundImage: [UIImage imageNamed:@"v2_coupon_verify_normal"] forBarMetrics:UIBarMetricsDefault];
    
    [self setupTableView];
    
    UIView *backgroundView = [[UIView alloc] initWithFrame:self.view.bounds];
    
    _backgroundView = backgroundView;
    
    backgroundView.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:backgroundView];
    
    [self loadData];
    
    [self registerNotification];
    
}

- (void)loadData {
    
    [SVProgressHUD showWithStatus:@"正在玩命加载中..."];
    
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    
//    [[BQListViewModel sharedViewModel] loadDataWithSuccessBlock:^{
//        
//        [SVProgressHUD dismiss];
//        
//        [self.backgroundView removeFromSuperview];
//        
//        [self.categoryTableView reloadData];
//        
//        [self.productTableView reloadData];
//        
//        [self.categoryTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionTop];
//        
//    } andFailureBlock:^(NSError *error) {
//       
//        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
//        
//    }];
    
    [[BQAccountManager sharedInstance] loadProductWithSuccessBlock:^{
        
        [SVProgressHUD dismiss];
        
        [self.backgroundView removeFromSuperview];
        
        [self.categoryTableView reloadData];
        
        [self.productTableView reloadData];
        
        [self.categoryTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionTop];
        
    } andFailureBlock:^(NSError *error) {
        
        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        
    }];
    
}

- (void)registerNotification{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickIncreaseButton:) name:ToValueNotificationName object:nil];
}


- (void)clickIncreaseButton: (NSNotification *)noti{
    
    BQProductModel *model = noti.object;
    
    CGPoint startPoint = [noti.userInfo[@"point"] CGPointValue];
    
    CGSize size = [noti.userInfo[@"size"] CGSizeValue];
    
    CGPoint controlPoint = CGPointMake(startPoint.x + 100, startPoint.y - 100);
    
    CGPoint endPoint = CGPointMake(_ScreenWidth / 4 * 2.5, _ScreenHeight - 44);
    
    UIImageView *imgIcon = [[UIImageView alloc] init];
    
    NSURL *imgUrl = [[NSURL alloc] initWithString:model.img];
    
    imgIcon.frame = CGRectMake(startPoint.x, startPoint.y, size.width, size.height);
    
    [imgIcon sd_setImageWithURL:imgUrl placeholderImage:[UIImage imageNamed:@"v2_placeholder_full_size"]];
    
    imgIcon.layer.cornerRadius = size.width / 2;
    
    imgIcon.layer.masksToBounds = YES;
    
    [kWindow addSubview:imgIcon];
    
    UIBezierPath *bezierPath = [UIBezierPath bezierPath];
    
    [bezierPath moveToPoint:startPoint];
    [bezierPath addQuadCurveToPoint:endPoint controlPoint:controlPoint];
    
    // 关键帧动画
    CAKeyframeAnimation *keyFrame = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    
    // 设置路径
    keyFrame.path = bezierPath.CGPath;
    
    // 设置动画时间
    keyFrame.duration = 1;
    
    // 保持动画的最新状态
    keyFrame.removedOnCompletion = NO;
    keyFrame.fillMode = kCAFillModeBoth;
    
    keyFrame.delegate = self;
    
    [keyFrame setValue:imgIcon forKey:@"imgIcon"];
    
    CABasicAnimation *basic = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    
    basic.toValue = @0;
    
    basic.duration = 1;
    
    
    
    [imgIcon.layer addAnimation:basic forKey:nil];
    [imgIcon.layer addAnimation:keyFrame forKey:nil];
    
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    
    UIImageView *imgIcon = [anim valueForKey:@"imgIcon"];
    
    [imgIcon removeFromSuperview];
    
}

- (void)setupTableView {
    
    self.automaticallyAdjustsScrollViewInsets = YES;
    
    _categoryTableView = [self creatTableView];
    
    _productTableView = [self creatTableView];
    
    _categoryTableView.backgroundColor = [UIColor ml_colorWithHex:0xEFEFEF];
    
    _categoryTableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 8);
    
    _productTableView.separatorInset = UIEdgeInsetsZero;
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.extendedLayoutIncludesOpaqueBars = YES;
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    _productTableView.rowHeight = 100;
    
    _productTableView.sectionHeaderHeight = 20;
    
    [_categoryTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.bottom.offset(0);
        make.width.mas_equalTo(self.view.frame.size.width / 4);
    }];
    
    [_productTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.bottom.offset(0);
        make.leading.equalTo(_categoryTableView.mas_trailing);
    }];
    
    [_categoryTableView registerClass:[BQCategoryTableViewCell class] forCellReuseIdentifier:category_id];
    
    [_productTableView registerNib:[UINib nibWithNibName:@"BQProductTableViewCell" bundle:nil] forCellReuseIdentifier:product_id];
    
}

- (UITableView *)creatTableView {
    
    UITableView *tableView = [UITableView new];
    
    tableView.delegate = self;
    
    tableView.dataSource = self;
    
    [self.view addSubview:tableView];
    
    return tableView;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UILabel *textLabel = [UILabel labelWithTextColor:[UIColor darkGrayColor] andTextSize:18 andTextContent:[NSString stringWithFormat:@"  %@", [BQAccountManager sharedInstance].categories[section].name]];
    
    textLabel.backgroundColor = [UIColor ml_colorWithHex:0xFAFAFA];
    
    textLabel.alpha = 0.5;
    
    return textLabel;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == _categoryTableView) {
        
        NSInteger index = indexPath.row;
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:index];
        
        [_productTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
        
    } else {
        
        BQDetailViewController *detailVC = [[BQDetailViewController alloc] init];
        
        detailVC.model = [BQAccountManager sharedInstance].categories[indexPath.section].products[indexPath.row];
        
        [self.navigationController pushViewController:detailVC animated:YES];
        
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        
    }
    
}

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView.isDragging || tableView.isDecelerating || tableView.isTracking) {
        
        if (tableView == _productTableView) {
            
            NSArray *indexPathArray = [tableView indexPathsForVisibleRows];
            
            NSIndexPath *indexPath = indexPathArray.firstObject;
            
            NSIndexPath *leftIndexPath = [NSIndexPath indexPathForRow:indexPath.section inSection:0];
            
            [_categoryTableView selectRowAtIndexPath:leftIndexPath animated:NO scrollPosition:UITableViewScrollPositionTop];
            
        }
        
    }
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return tableView == _categoryTableView ? 1 : [BQAccountManager sharedInstance].categories.count;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return tableView == _categoryTableView ? [BQAccountManager sharedInstance].categories.count : [BQAccountManager sharedInstance].categories[section].products.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == _categoryTableView) {
        BQCategoryTableViewCell *categoryCell = [tableView dequeueReusableCellWithIdentifier:category_id forIndexPath:indexPath];
        
        categoryCell.textLabel.text = [BQAccountManager sharedInstance].categories[indexPath.row].name;
        
        return categoryCell;
        
    } else {
        
        BQProductTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:product_id forIndexPath:indexPath];
        
        cell.model = [BQAccountManager sharedInstance].categories[indexPath.section].products[indexPath.row];
        
        return cell;
        
    }
    
}

@end
